<template>
  <div class="Tmap">
    <div class="service">
      <Select
        v-if="searchMap"
        v-model:value="data.serviceAddress"
        show-search
        placeholder="请输入地址"
        style="width: 300px; margin-right: 10px"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        :not-found-content="null"
        :options="data.serviceList"
        allowClear
        @search="handleSearch"
        @change="handleChange"
      >
      </Select>
      <Select
        v-if="isDistance"
        ref="select"
        v-model:value="data.distance"
        style="width: 120px; margin-right: 10px"
        @change="handleDistance"
      >
        <SelectOption :value="item.value" v-for="(item, index) in data.distanceList" :key="index">{{
          item.label
        }}</SelectOption>
      </Select>
      <TimePicker v-model:value="data.startTime" style="margin-right: 10px" v-if="isTimePicker" />
      <TimePicker v-model:value="data.endTime" v-if="isTimePicker" />
    </div>
    <div id="TxMap"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, toRefs, ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue';
import { Select, SelectOption } from 'ant-design-vue';
import markerSrc from '/@/assets/images/map-marker.png';
import moment, { Moment } from 'moment';
import { TimePicker } from 'ant-design-vue';

import { jsonp } from 'vue-jsonp';
import { log } from 'console';
const props = defineProps({
  lat: { type: Number, default: 0 },
  lng: { type: Number, default: 0 },
  address: { type: String, default: '' },
  serviceAddress: { type: String, default: '' },
  zoom: { type: Number, default: 10 },
  viewMode: { type: String, default: '2D' },
  showControl: { type: Boolean, default: true },
  isLocation: { type: Boolean, default: true },
  searchMap: { type: Boolean, default: false },
  isClick: { type: Boolean, default: false },
  isCircle: { type: Boolean, default: false },
  isMultiple: { type: Boolean, default: false },
  distance: { type: Number, default: 300 },
  isDistance: { type: Boolean, default: false },
  isTimePicker: { type: Boolean, default: false },
  startTime: { type: Object, default: {} },
  endTime: { type: Object, default: {} },
});
//发送事件
const emit = defineEmits(['update']);

const data: any = reactive({
  lat: props.lat,
  lng: props.lng,
  address: props.address,
  zoom: props.zoom, //缩放
  viewMode: props.viewMode, //缩放
  showControl: props.showControl, //缩放
  TMapKey: 'UPOBZ-VZSCD-4PT4A-H4EQU-TUIUF-N4F4A',
  TMapKeyName: 'houtai',
  markerSrc: markerSrc,
  serviceAddress: props.serviceAddress ? props.serviceAddress : null,
  serviceList: [],
  distance: props.distance,
  distanceList: [
    {
      label: '300米',
      value: 300,
    },
    {
      label: '500米',
      value: 500,
    },
    {
      label: '800米',
      value: 800,
    },
    {
      label: '1000米',
      value: 1000,
    },
    {
      label: '1500米',
      value: 1500,
    },
    {
      label: '6000米',
      value: 6000,
    },
  ],
  startTime: props.startTime,
  endTime: props.endTime,
});
let map, marker, circle, geolocation, center;
const initMap = () => {
  // 定义地图中心点坐标
  center = new window.TMap.LatLng(data.lat, data.lng);
  map = new window.TMap.Map('TxMap', {
    center: center, // 设置地图中心点坐标
    zoom: data.zoom, // 设置地图缩放级别
    viewMode: data.viewMode, // 设置2D模式
    showControl: data.showControl, // 去掉控件
  });
  markerLayer(); // 标记地图
  drawCircle(); //设置距离
  if (props.isClick) {
    map.on('click', (evt) => {
      const evtModel = {
        lat: evt.latLng.getLat().toFixed(6),
        lng: evt.latLng.getLng().toFixed(6),
      };
      center = new window.TMap.LatLng(evtModel.lat, evtModel.lng);
      drawCircle(); //设置距离
      //逆地址解析
      filteredResults(`${evtModel.lat},${evtModel.lng}`, '', (b) => {
        marker.updateGeometries({
          id: 'marker',
          position: evt.latLng,
          styleId: 'markerStyle',
          content: data.serviceAddress,
        });
      });

      setCenter(evtModel.lat, evtModel.lng);
    });
  }
};
console.log('我是map的Propos',props);

//标记地图
const markerLayer = () => {
  marker = new window.TMap.MultiMarker({
    map: map, //指定地图容器
    styles: {
      markerStyle: new window.TMap.MarkerStyle({
        // 点标注的相关样式
        width: 25, // 宽度
        height: 25, // 高度
        anchor: { x: 17, y: 23 }, // 标注点图片的锚点位置
        src: data.markerSrc, // 标注点图片url或base64地址
        color: '#B45F04', // 标注点文本颜色
        size: 20, // 标注点文本文字大小
        direction: 'top', // 标注点文本文字相对于标注点图片的方位
        offset: { x: 0, y: 0 }, // 标注点文本文字基于direction方位的偏移属性
        strokeColor: '#fff', // 标注点文本描边颜色
        strokeWidth: 2, // 标注点文本描边宽度
      }),
    },
    //点标记数据数组
    geometries: [
      {
        id: 'marker', //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
        styleId: 'markerStyle', //指定样式id
        position: new window.TMap.LatLng(data.lat, data.lng), //点标记坐标位置
        content: data.serviceAddress,
      },
    ],
  });
};

//绘制圆圈距离
const drawCircle = () => {
  if (!props.isCircle) {
    return;
  }
  if (circle) {
    circle.setMap(null);
  }

  // let center = new window.TMap.LatLng(data.lat, data.lng);
  circle = new window.TMap.MultiCircle({
    map,
    styles: {
      // 设置圆形样式
      circle: new TMap.CircleStyle({
        color: 'rgba(41,91,255,0.16)',
        showBorder: true,
        borderColor: 'rgba(41,91,255,1)',
        borderWidth: 2,
      }),
    },
    geometries: [
      {
        styleId: 'circle',
        center: center,
        radius: data.distance,
      },
    ],
  });
};

//获取中心点
function setCenter(lat, lng) {
  map.setCenter(new window.TMap.LatLng(lat, lng)); //坐标为天安门
}
//获取定位
const getCurrentLocation = () => {
  geolocation = new (window as any).qq.maps.Geolocation(data.TMapKey, data.TMapKeyName);
  geolocation.getLocation(
    (res: any) => {
      console.log('定位成功', res);
      const location = `${res.lat},${res.lng}`;
      filteredResults(location, '', (d: any) => {
        nextTick(() => {
          initMap();
        });
      });
    },
    (err: any) => {
      console.log('定位失败', err);
    },
    { timeout: 100000 },
  );
};
//开启并获取定位

if (props.isLocation && !props.serviceAddress) {
  getCurrentLocation();
}

//搜索
const querySearch = async (queryString: string, cb: any): Promise<any> => {
  jsonp('https://apis.map.qq.com/ws/place/v1/suggestion', {
    key: data.TMapKey,
    keyword: queryString,
    output: 'jsonp', // output必须jsonp   不然会超时
  })
    .then((res) => {
      let { data } = res;
      let serviceList = data.map((item) => {
        let obj = {
          value: `${item.location.lat},${item.location.lng},${item.address},${item.title}`,
          label: `${item.address}${item.title}`,
        };
        return obj;
      });
      cb(serviceList);
    })
    .catch((error) => {
      console.log(error);
    });
};
//搜索
const handleSearch = (val: string) => {
  querySearch(val, (d: any[]) => (data.serviceList = d));
};
//选择地址
const handleChange = (val: string) => {
  try {
    if (val) {
      const valArr = val.split(',') || [];
      const updateData = {
        lat: valArr[0],
        lng: valArr[1],
        address: `${valArr[2]}${valArr[3]}`,
      };
      data.address = updateData.address;
      data.serviceAddress = updateData.address;
      data.lng = updateData.lng;
      data.lat = updateData.lat;
      center = new window.TMap.LatLng(updateData.lat, updateData.lng);
      drawCircle();
      marker.updateGeometries({
        id: 'marker',
        position: center,
        styleId: 'markerStyle',
        content: updateData.address,
      });
      setCenter(updateData.lat, updateData.lng);
      emit('update', updateData);
    }
  } catch (error) {}
};
//选择距离
const handleDistance = (val: string) => {
  drawCircle();
};

// 逆地址解析
const filteredResults = (location?: string, address?: string, callback?: any) => {
  const params = {
    key: data.TMapKey,
    output: 'jsonp',
  };
  if (location) {
    params.location = location;
  }
  if (address) {
    params.address = address;
  }
  jsonp('https://apis.map.qq.com/ws/geocoder/v1', params)
    .then((res) => {
      console.log(res);
      if (res.status == 0) {
        // 通过地址得到经纬度
        data.address = res.result.address;
        data.serviceAddress = res.result.address;
        data.lng = res.result.location.lng;
        data.lat = res.result.location.lat;
        const updateData = {
          lat: data.lat,
          lng: data.lng,
          address: data.address,
          distance: data.distance,
        };
        if (callback) {
          callback(true);
        }
        emit('update', updateData);
      }
    })
    .catch((e) => {
      console.log(e);
    });
};

const loadScripts = (array, callback) => {
  const loader = function (src, handler) {
    const script = document.createElement('script');
    script.src = src;
    script.onload = script.onreadystatechange = function () {
      script.onreadystatechange = script.onload = null;
      handler();
    };
    const head = document.getElementsByTagName('head')[0];
    (head || document.body).appendChild(script);
  };
  (function run() {
    if (array.length != 0) {
      loader(array.shift(), run);
    } else {
      callback && callback();
    }
  })();
};
onMounted(() => {
  loadScripts(
    [
      'https://map.qq.com/api/gljs?v=1.exp&key=' + data.TMapKey,
      'https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js',
    ],
    function () {
      if (!props.isLocation || props.serviceAddress) {
        initMap();
      }
    },
  );
});

defineExpose({
  data,
});
onBeforeUnmount(() => {
  // 切换路由的时候可能创建了多个实例，可以使用destroy销毁地图
  if (map) {
    console.log('我是销毁');

    map.destroy();
  }
});
</script>

<style lang="less" scoped>
.timePicker {
  display: flex;
}
.Tmap {
  width: 100%;
  height: 100%;
  position: relative;
  .service {
    position: absolute;
    left: 10px;
    top: 10px;
    z-index: 9999;
  }
}
#TxMap {
  width: 100%;
  height: 100%;
}
</style>